package com.example.springbooksystem.controller;

import com.example.springbooksystem.constant.Constants;
import com.example.springbooksystem.model.UserInfo;
import com.example.springbooksystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2023-11-07
 * @time: 22:53:17
 */
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public boolean login(String name, String password, HttpServletRequest request) {
        // 1. 参数检验
        if (!StringUtils.hasLength(name)||!StringUtils.hasLength(password)) {
            return false;
        }
        // 2. 处理逻辑
        // 2.1 依据 name 在数据库中查询用户
        UserInfo userInfo = userService.queryUserByName(name);
        // 2.2 该用户是否合法
        if (userInfo == null  || userInfo.getId() < 1) {
            // 不存在
            return false;
        }
        // 2.3 密码正确, 存入 session
        if (password.equals(userInfo.getPassword())) {
            HttpSession session = request.getSession();
            userInfo.setPassword("");
            session.setAttribute(Constants.SESSION_USER_KEY,userInfo);
            return true;
        }
        return false;
    }
}
